#include "yunw_mesh_service.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "data_type.h"
// #include <cjson/cJSON.h>

// 用于存储HTTP响应数据的结构体
struct ResponseData {
    char *data;
    size_t size;
};

// 写回调函数，用于接收HTTP响应数据
static size_t write_callback(void *contents, size_t size, size_t nmemb, void *userp) {
    size_t realsize = size * nmemb;
    struct ResponseData *mem = (struct ResponseData *)userp;

    char *ptr = realloc(mem->data, mem->size + realsize + 1);
    if(!ptr) {
        printf("内存分配失败\n");
        return 0;
    }

    mem->data = ptr;
    memcpy(&(mem->data[mem->size]), contents, realsize);
    mem->size += realsize;
    mem->data[mem->size] = 0;

    return realsize;
}
#if 0
// 解析JSON响应，示例中假设返回的是{"status":"success","data":"some data"}
void parse_json_response(const char *json_response) {
    cJSON *root = cJSON_Parse(json_response);
    if (root == NULL) {
        const char *error_ptr = cJSON_GetErrorPtr();
        if (error_ptr != NULL) {
            fprintf(stderr, "JSON解析错误: %s\n", error_ptr);
        }
        return;
    }

    cJSON *status = cJSON_GetObjectItemCaseSensitive(root, "status");
    if (cJSON_IsString(status) && (status->valuestring != NULL)) {
        printf("状态: %s\n", status->valuestring);
    }

    cJSON *data = cJSON_GetObjectItemCaseSensitive(root, "data");
    if (cJSON_IsString(data) && (data->valuestring != NULL)) {
        printf("数据: %s\n", data->valuestring);
    }

    cJSON_Delete(root);
}
#endif
#define BASE_URL    "http://172.20.10.3/command/"
CURL *curl;
void curl_init(void){
    // 初始化libcurl
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
}


void login(const char *username, const char *password){
    CURLcode res;
    struct ResponseData chunk;
    chunk.data = malloc(1);
    chunk.size = 0;
    if(curl) {
        char url[128] = {0};
        sprintf(url, "http://%s/command/login", meshCfg.ipaddr);
        // 设置登录接口的URL
        curl_easy_setopt(curl, CURLOPT_URL, url);

        // 设置POST请求
        curl_easy_setopt(curl, CURLOPT_POST, 1L);

        // 构造JSON登录数据
        char json_data[128];
        sprintf(json_data, "{\"username\": \"%s\", \"password\": \"%s\"}", username, password);

        // 设置HTTP头
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        // 设置POST数据
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data);
        curl_easy_setopt(curl, CURLOPT_COOKIEJAR, "cookies.txt"); // 保存Cookie
        // 设置写回调和响应数据存储
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);

        // 执行登录请求
        res = curl_easy_perform(curl);

        // 检查登录结果
        if(res != CURLE_OK) {
            fprintf(stderr, "登录请求失败: %s\n", curl_easy_strerror(res));
        } else {
            printf("登录响应: %s\n", chunk.data);
            // 解析登录响应
            // parse_json_response(chunk.data);
        }
        curl_slist_free_all(headers);
    }
    free(chunk.data);
}
/**
 * 获取ip地址
 */
void getipaddress(){
    CURLcode res;
    struct ResponseData chunk;
    chunk.data = malloc(1);
    chunk.size = 0;
    if(curl) {
        char url[128] = {0};
        sprintf(url, "http://%s/command/getipaddress", meshCfg.ipaddr);
        // 现在访问受保护的接口，使用相同的curl句柄（Cookie会自动保存和发送）
        curl_easy_setopt(curl, CURLOPT_URL, url);
        // 改为GET请求
        curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
        // 设置HTTP头
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "cookies.txt"); // 读取并发送Cookie
        // 设置写回调和响应数据存储
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
        printf("1\n");
        // 执行受保护接口的请求
        res = curl_easy_perform(curl);
        printf("2\n");
        if(res != CURLE_OK) {
            fprintf(stderr, "API请求失败: %s\n", curl_easy_strerror(res));
        } else {
            printf("API响应: %s\n", chunk.data);
            // 解析API响应
            //parse_json_response(chunk.data);
        }
        curl_slist_free_all(headers);
    }
    free(chunk.data);
}
/**
 * 设置IP地址
 */
void setipaddress(const char *ip) {
    CURLcode res;
    struct ResponseData chunk;
    chunk.data = malloc(1);
    chunk.size = 0;
    if(curl) {
        char url[128] = {0};
        sprintf(url, "http://%s/command/setipaddress", meshCfg.ipaddr);
        // 现在访问受保护的接口，使用相同的curl句柄（Cookie会自动保存和发送）
        curl_easy_setopt(curl, CURLOPT_URL, url);
        // 改为GET请求
        curl_easy_setopt(curl, CURLOPT_POST, 1L);
        // 构造JSON登录数据
        char json_data[128];
        sprintf(json_data, "{\"ipaddress\": \"%s\"}", ip);

        // 设置HTTP头
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        // 设置POST数据
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data);
        curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "cookies.txt"); // 读取并发送Cookie
        // 设置写回调和响应数据存储
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
        // 执行受保护接口的请求
        res = curl_easy_perform(curl);

        if(res != CURLE_OK) {
            fprintf(stderr, "API请求失败: %s\n", curl_easy_strerror(res));
        } else {
            printf("API响应: %s\n", chunk.data);
            // 解析API响应
            //parse_json_response(chunk.data);
        }
        curl_slist_free_all(headers);
    }
    free(chunk.data);
}
void getwlan0mode(void){
    CURLcode res;
    struct ResponseData chunk;
    chunk.data = malloc(1);
    chunk.size = 0;
    if(curl) {
        char url[128] = {0};
        sprintf(url, "http://%s/command/getwlan0mode", meshCfg.ipaddr);
        // 现在访问受保护的接口，使用相同的curl句柄（Cookie会自动保存和发送）
        curl_easy_setopt(curl, CURLOPT_URL, url);
        // 改为GET请求
        curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);

        // 设置HTTP头
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        // 设置POST数据
        curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "cookies.txt"); // 读取并发送Cookie
        // 设置写回调和响应数据存储
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
        // 执行受保护接口的请求
        res = curl_easy_perform(curl);

        if(res != CURLE_OK) {
            fprintf(stderr, "API请求失败: %s\n", curl_easy_strerror(res));
        } else {
            printf("API响应: %s\n", chunk.data);
            // 解析API响应
            //parse_json_response(chunk.data);
        }
        curl_slist_free_all(headers);
    }
    free(chunk.data);
}
/**
 * 设置无线模式命令，0: AP，1: STA, 2: MESH
 */
void setwlanmode(const int iwlan, const char *mode) {
    CURLcode res;
    struct ResponseData chunk;
    chunk.data = malloc(1);
    chunk.size = 0;
    if(curl) {
        char url[128] = {0};
        sprintf(url, "http://%s/command/setwlanmode", meshCfg.ipaddr);
        // 现在访问受保护的接口，使用相同的curl句柄（Cookie会自动保存和发送）
        curl_easy_setopt(curl, CURLOPT_URL, url);
        // 改为GET请求
        curl_easy_setopt(curl, CURLOPT_POST, 1L);
        // 构造JSON登录数据
        char json_data[128];
        sprintf(json_data, "{\"iwlan\": \"%d\",\"mode\":\"%s\"}", iwlan, mode);

        // 设置HTTP头
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        // 设置POST数据
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data);
        curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "cookies.txt"); // 读取并发送Cookie
        // 设置写回调和响应数据存储
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
        // 执行受保护接口的请求
        res = curl_easy_perform(curl);

        if(res != CURLE_OK) {
            fprintf(stderr, "API请求失败: %s\n", curl_easy_strerror(res));
        } else {
            printf("API响应: %s\n", chunk.data);
            // 解析API响应
            //parse_json_response(chunk.data);
        }
        curl_slist_free_all(headers);
    }
    free(chunk.data);
}

void getwlan0ssid(void){
    CURLcode res;
    struct ResponseData chunk;
    chunk.data = malloc(1);
    chunk.size = 0;
    if(curl) {
        char url[128] = {0};
        sprintf(url, "http://%s/command/getwlan0ssid", meshCfg.ipaddr);
        // 现在访问受保护的接口，使用相同的curl句柄（Cookie会自动保存和发送）
        curl_easy_setopt(curl, CURLOPT_URL, url);
        // 改为GET请求
        curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);

        // 设置HTTP头
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        // 设置POST数据
        curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "cookies.txt"); // 读取并发送Cookie
        // 设置写回调和响应数据存储
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
        // 执行受保护接口的请求
        res = curl_easy_perform(curl);

        if(res != CURLE_OK) {
            fprintf(stderr, "API请求失败: %s\n", curl_easy_strerror(res));
        } else {
            printf("API响应: %s\n", chunk.data);
            // 解析API响应
            //parse_json_response(chunk.data);
        }
        curl_slist_free_all(headers);
    }
    free(chunk.data);
}
/**
 * 设置无线SSID命令，AP，STA，MESH下SSID密码一致可以连接
 */
void setwifissid(const int iwlan, const char *ssid) {
    CURLcode res;
    struct ResponseData chunk;
    chunk.data = malloc(1);
    chunk.size = 0;
    if(curl) {
        char url[128] = {0};
        sprintf(url, "http://%s/command/setwifissid", meshCfg.ipaddr);
        // 现在访问受保护的接口，使用相同的curl句柄（Cookie会自动保存和发送）
        curl_easy_setopt(curl, CURLOPT_URL, url);
        // 改为GET请求
        curl_easy_setopt(curl, CURLOPT_POST, 1L);
        // 构造JSON登录数据
        char json_data[128];
        sprintf(json_data, "{\"iwlan\": \"%d\",\"ssid\":\"%s\"}", iwlan, ssid);

        // 设置HTTP头
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        // 设置POST数据
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data);
        curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "cookies.txt"); // 读取并发送Cookie
        // 设置写回调和响应数据存储
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
        // 执行受保护接口的请求
        res = curl_easy_perform(curl);

        if(res != CURLE_OK) {
            fprintf(stderr, "API请求失败: %s\n", curl_easy_strerror(res));
        } else {
            printf("API响应: %s\n", chunk.data);
            // 解析API响应
            //parse_json_response(chunk.data);
        }
        curl_slist_free_all(headers);
    }
    free(chunk.data);
}
void getwlan0psk(void){
    CURLcode res;
    struct ResponseData chunk;
    chunk.data = malloc(1);
    chunk.size = 0;
    if(curl) {
        char url[128] = {0};
        sprintf(url, "http://%s/command/getwlan0psk", meshCfg.ipaddr);
        // 现在访问受保护的接口，使用相同的curl句柄（Cookie会自动保存和发送）
        curl_easy_setopt(curl, CURLOPT_URL, url);
        // 改为GET请求
        curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);

        // 设置HTTP头
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        // 设置POST数据
        curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "cookies.txt"); // 读取并发送Cookie
        // 设置写回调和响应数据存储
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
        // 执行受保护接口的请求
        res = curl_easy_perform(curl);

        if(res != CURLE_OK) {
            fprintf(stderr, "API请求失败: %s\n", curl_easy_strerror(res));
        } else {
            printf("API响应: %s\n", chunk.data);
            // 解析API响应
            //parse_json_response(chunk.data);
        }
        curl_slist_free_all(headers);
    }
    free(chunk.data);
}
/**
 * 设置无线密码命令，AP，STA，MESH下SSID密码一致可以连接。
 */
void setwifipassword(const int iwlan, const char *password) {
    CURLcode res;
    struct ResponseData chunk;
    chunk.data = malloc(1);
    chunk.size = 0;
    if(curl) {
        char url[128] = {0};
        sprintf(url, "http://%s/command/setwifipassword", meshCfg.ipaddr);
        // 现在访问受保护的接口，使用相同的curl句柄（Cookie会自动保存和发送）
        curl_easy_setopt(curl, CURLOPT_URL, url);
        // 改为GET请求
        curl_easy_setopt(curl, CURLOPT_POST, 1L);
        // 构造JSON登录数据
        char json_data[128];
        sprintf(json_data, "{\"iwlan\": \"%d\",\"password\":\"%s\"}", iwlan, password);

        // 设置HTTP头
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        // 设置POST数据
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data);
        curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "cookies.txt"); // 读取并发送Cookie
        // 设置写回调和响应数据存储
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
        // 执行受保护接口的请求
        res = curl_easy_perform(curl);

        if(res != CURLE_OK) {
            fprintf(stderr, "API请求失败: %s\n", curl_easy_strerror(res));
        } else {
            printf("API响应: %s\n", chunk.data);
            // 解析API响应
            //parse_json_response(chunk.data);
        }
        curl_slist_free_all(headers);
    }
    free(chunk.data);
}
/**
 * 设置无线密码命令，AP，STA，MESH下SSID密码一致可以连接。
 */
void setssidpassword(const int iwlan, const char *ssid, const char *password) {
    CURLcode res;
    struct ResponseData chunk;
    chunk.data = malloc(1);
    chunk.size = 0;
    if(curl) {
        char url[128] = {0};
        sprintf(url, "http://%s/command/setssidpassword", meshCfg.ipaddr);
        // 现在访问受保护的接口，使用相同的curl句柄（Cookie会自动保存和发送）
        curl_easy_setopt(curl, CURLOPT_URL, url);
        // 改为GET请求
        curl_easy_setopt(curl, CURLOPT_POST, 1L);
        // 构造JSON登录数据
        char json_data[128];
        sprintf(json_data, "{\"iwlan\": \"%d\",\"ssid\":\"%s\",\"password\":\"%s\"}", iwlan, ssid, password);

        // 设置HTTP头
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        // 设置POST数据
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data);
        curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "cookies.txt"); // 读取并发送Cookie
        // 设置写回调和响应数据存储
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
        // 执行受保护接口的请求
        res = curl_easy_perform(curl);

        if(res != CURLE_OK) {
            fprintf(stderr, "API请求失败: %s\n", curl_easy_strerror(res));
        } else {
            printf("API响应: %s\n", chunk.data);
            // 解析API响应
            //parse_json_response(chunk.data);
        }
        curl_slist_free_all(headers);
    }
    free(chunk.data);
}
/**
 * 读取系统和信号状态命令，csw2205对应csw520a，csw2206对应csw620a
 */
char* sysstatus(void){
    CURLcode res;
    struct ResponseData chunk;
    chunk.data = malloc(1);
    chunk.size = 0;
    if(curl) {
        char url[128] = {0};
        sprintf(url, "http://%s/command/sysstatus", meshCfg.ipaddr);
        // 现在访问受保护的接口，使用相同的curl句柄（Cookie会自动保存和发送）
        curl_easy_setopt(curl, CURLOPT_URL, url);
        // 改为GET请求
        curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);

        // 设置HTTP头
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        // 设置POST数据
        curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "cookies.txt"); // 读取并发送Cookie
        // 设置写回调和响应数据存储
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
        // 执行受保护接口的请求
        res = curl_easy_perform(curl);

        if(res != CURLE_OK) {
            fprintf(stderr, "API请求失败: %s\n", curl_easy_strerror(res));
        } else {
            printf("API响应: %s\n", chunk.data);
            // 解析API响应
            //parse_json_response(chunk.data);
            curl_slist_free_all(headers);
            return chunk.data;
        }
        curl_slist_free_all(headers);
    }
    free(chunk.data);
    return NULL;
}
/**
 * 扫描信道噪声命令
 */
void scannoise(const int iwlan) {
    CURLcode res;
    struct ResponseData chunk;
    chunk.data = malloc(1);
    chunk.size = 0;
    if(curl) {
        char url[128] = {0};
        sprintf(url, "http://%s/command/scannoise", meshCfg.ipaddr);
        // 现在访问受保护的接口，使用相同的curl句柄（Cookie会自动保存和发送）
        curl_easy_setopt(curl, CURLOPT_URL, url);
        // 改为GET请求
        curl_easy_setopt(curl, CURLOPT_POST, 1L);
        // 构造JSON登录数据
        char json_data[128];
        sprintf(json_data, "{\"iwlan\": \"%d\"}", iwlan);

        // 设置HTTP头
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        // 设置POST数据
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data);
        curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "cookies.txt"); // 读取并发送Cookie
        // 设置写回调和响应数据存储
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
        // 执行受保护接口的请求
        res = curl_easy_perform(curl);

        if(res != CURLE_OK) {
            fprintf(stderr, "API请求失败: %s\n", curl_easy_strerror(res));
        } else {
            printf("API响应: %s\n", chunk.data);
            // 解析API响应
            //parse_json_response(chunk.data);
        }
        curl_slist_free_all(headers);
    }
    free(chunk.data);
}
/**
 * 扫描AP热点命令
 */
void scanaphost(const int iwlan) {
    CURLcode res;
    struct ResponseData chunk;
    chunk.data = malloc(1);
    chunk.size = 0;
    if(curl) {
        char url[128] = {0};
        sprintf(url, "http://%s/command/scanaphost", meshCfg.ipaddr);
        // 现在访问受保护的接口，使用相同的curl句柄（Cookie会自动保存和发送）
        curl_easy_setopt(curl, CURLOPT_URL, url);
        // 改为GET请求
        curl_easy_setopt(curl, CURLOPT_POST, 1L);
        // 构造JSON登录数据
        char json_data[128];
        sprintf(json_data, "{\"iwlan\": \"%d\"}", iwlan);

        // 设置HTTP头
        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        // 设置POST数据
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data);
        curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "cookies.txt"); // 读取并发送Cookie
        // 设置写回调和响应数据存储
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
        // 执行受保护接口的请求
        res = curl_easy_perform(curl);

        if(res != CURLE_OK) {
            fprintf(stderr, "API请求失败: %s\n", curl_easy_strerror(res));
        } else {
            printf("API响应: %s\n", chunk.data);
            // 解析API响应
            //parse_json_response(chunk.data);
        }
        curl_slist_free_all(headers);
    }
    free(chunk.data);
}

void clean_curl(){
    if(curl){
        curl_easy_cleanup(curl);
    }
    curl_global_cleanup();
}
